package courseService

import (
	"cs/src/config"
	"cs/src/helper"
	"cs/src/libs/fileSystem"
	"cs/src/libs/logs"
	"cs/src/model"
	"encoding/json"
	"log"
	"os"
)

/**
初始化需要存储的data数据
*/
var courselist []model.Course
var redisData = make(map[string][]string)

func init() {
	dataSource := config.Get("app", "datasource")

	if dataSource == "file" {
		logs.Info(dataSource)
		getCourseListFromJson()
	} else {
		log.Fatal("数据将来源于sql")
	}
}

/**
获取需要生成的redis数据
*/
func GetRedisData() map[string][]string {

	//开始处理课程数据
	handleCourseList()

	return redisData
}

/**
从json文件获取课程列表数据
*/
func getCourseListFromJson() {
	//解析json文件
	filePath := fileSystem.GetFilePath("data/classplan.json")

	file, err := os.OpenFile(filePath, os.O_RDONLY, 066)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	//var dataJson map[string]interface{}  如果没有使用struct接受，则可以使用这种方式
	decodeError := json.NewDecoder(file).Decode(&courselist)
	if decodeError != nil {
		panic(decodeError)
	}
}

/**
处理json数据
*/
func handleCourseList() {

	//循环输出json数组
	for _, courseInfo := range courselist {
		//json对象赋值到map上面
		for _, keyA := range helper.BASE_DATA_SEARCH_FIELDS {

			//组合key
			keyPre := "city_id_" + courseInfo.Get("city_id") + "|tid_" + courseInfo.Get("tid") + "|" + keyA + "_" + courseInfo.Get(keyA)
			keyPreOption := "option|" + keyPre
			keyPreSearch := "search|" + keyPre

			for j := 0; j < len(helper.BASE_DATA_SEARCH_FIELDS); j++ {

				keyB := helper.BASE_DATA_SEARCH_FIELDS[j]

				if keyA == keyB {
					continue
				}

				//创建option数据
				createOptionData(keyPreOption, keyB, courseInfo)

				//创建search数据
				createSearchData(keyPreSearch, courseInfo.Get("id"))
			}
		}
	}
}

/**
创建option数据
格式：option|city_id_1|tid_18|classroom_id_488|campus_id
*/
func createOptionData(keyPreOption string, keyB string, courseInfo model.Course) {
	valueKeyOption := keyPreOption + "|" + keyB

	_, ok := redisData[valueKeyOption]
	if !ok {
		valueKeyMap := []string{}
		redisData[valueKeyOption] = valueKeyMap
	}
	redisData[valueKeyOption] = append(redisData[valueKeyOption], courseInfo.Get(keyB))
}

/**
创建search数据
格式：search|city_id_1|tid_18|classroom_id_144
*/
func createSearchData(keyPreSearch string, coureseId string) {
	valueKeySearch := keyPreSearch

	_, ok := redisData[valueKeySearch]
	if !ok {
		valueKeyMap := []string{}
		redisData[valueKeySearch] = valueKeyMap
	}
	redisData[valueKeySearch] = append(redisData[valueKeySearch], coureseId)
}
